<script setup>
	import { ref } from 'vue'
	import { loginByPassword } from '@/services/user'
	import { useUserStore } from '@/stores/user.js'

	const userStore = useUserStore()
	const formRules = {
		mobile: {
			rules: [
				{
					required: true,
					errorMessage: '请填写手机号码',
				},
				{ pattern: '^1\\d{10}$', errorMessage: '手机号码格式不正确' },
			],
		},
		password: {
			rules: [
				{ required: true, errorMessage: '请填写密码' },
				{ minLength: 3, errorMessage: '密码长度至少 {minLength}个字符' },
			],
		},
	}
	const formData = ref({
		mobile: '13230000067',
		password: 'abc12345',
	})
	const form = ref()
	const onsubmit = () => {
		form.value
			.validate()
			.then(async (res) => {
				if (!checked.value) return uni.utils.toast('请勾选用户协议')
				const { code, message, data } = await loginByPassword({
					...formData.value,
				})
				if (code !== 10000) return uni.utils.toast(message)
				userStore.token = data.token
				userStore.userId = data.id
				if (userStore.openType === 'switchTab')
					return uni.switchTab({
						url: userStore.redirectURL,
					})

				if (userStore.redirectURL !== '/pages/login/index')
					return uni.navigateTo({
						url: userStore.redirectURL,
					})

				uni.switchTab({
					url: '/pages/index/index',
				})
			})
			.catch((err) => {
				console.log(err)
			})
	}
	const checked = ref(false)
	const clickRadio = () => {
		checked.value = !checked.value
	}
</script>
<template>
	<uni-forms
		ref="form"
		:rules="formRules"
		:modelValue="formData"
		class="uni-forms"
	>
		<uni-forms-item name="mobile" class="uni-forms-item">
			<uni-easyinput
				:input-border="false"
				:clearable="false"
				v-model="formData.mobile"
				placeholder="请输入手机号"
				placeholder-style="color: #C3C3C5"
			/>
		</uni-forms-item>
		<uni-forms-item name="password" class="uni-forms-item">
			<uni-easyinput
				:input-border="false"
				:clearable="false"
				v-model="formData.password"
				placeholder="请输入密码"
				placeholder-style="color: #C3C3C5"
				type="password"
			/>
		</uni-forms-item>
		<view class="agreement">
			<radio :checked="checked" color="#16c2a3" @click="clickRadio">
				我已同意
				<text class="link">用户协议</text>
				及
				<text class="link">隐私协议</text></radio
			>
		</view>
		<button class="uni-button" @click="onsubmit">登 录</button>
		<navigator url="" class="uni-navigator" hover-class="none">
			忘记密码？
		</navigator>
	</uni-forms>
</template>

<script>
	export default {
		options: {
			styleIsolation: 'shared',
		},
	}
</script>
<style scoped>
	@import './styles.scss';
</style>
